/**
 * Copyright 2007-2008. Chongqing First Information & Network Co., Ltd. All
 * rights reserved. <a>http://www.cqfirst.com.cn</a>
 */
package com.cqcis.uip.base.framework.handlers.impl;


import com.cqcis.uip.base.framework.common.Task;
import com.cqcis.uip.base.framework.core.RegisteredServiceContext;
import com.cqcis.uip.base.framework.core.Service;
import com.cqcis.uip.base.framework.core.ServiceRoleIgnore;
import com.cqcis.uip.base.framework.core.TaskResultProcessor;
import com.cqcis.uip.base.framework.handlers.AfterService;
import com.cqcis.uip.base.framework.handlers.BeforeService;
import com.cqcis.uip.base.framework.handlers.ClientService;
import com.cqcis.uip.base.framework.handlers.common.AbstractClientHandler;

/**
 * @author huangmy
 * @date   2007-12-20
 */
@ServiceRoleIgnore
public class DefaultClientHandler extends AbstractClientHandler {
	private BeforeService beforeService;
	private ClientService service;
	private AfterService afterService;
	
	public boolean processResult(Task result) {
		if (service instanceof TaskResultProcessor) {
			return ((TaskResultProcessor)service).processResult(result);
		}
		
		return true;
	}
	
	@Override
	public void start(RegisteredServiceContext serviceContext) throws Exception {		
		super.start(serviceContext);
		
		if (service == null) {
			throw new RuntimeException("the handler's depended service must not be null.");
		}
		
		if (service instanceof Service) {
			((Service)service).start(serviceContext);
		}
	}
	
	@Override
	public void stop(RegisteredServiceContext serviceContext) throws Exception {
		if (service instanceof Service) {
			((Service)service).stop(serviceContext);
		}
		
		super.stop(serviceContext);
	}
	
	@Override
	public Object doMessageSend(Task task) throws Exception {		
		return service.doMessageSend(task);
	}
	
	@Override
	public void doMessageReceived(Object message, Task task) throws Exception {		
		service.doMessageReceived(message, task);
	}
	
	protected Task getBeforeTask(Object message) {
    	return beforeService == null ? null : beforeService.getTask(message);
    }
	
	protected Task getAfterTask(Object writeMessage) {
		return afterService == null ? null : afterService.getTask(writeMessage);
	}

	public void setService(ClientService service) {
		this.service = service;
	}
	
	public void setBeforeService(BeforeService beforeService) {
		this.beforeService = beforeService;
	}

	public void setAfterService(AfterService afterService) {
		this.afterService = afterService;
	}
}
